package MianCalPak;

import java.io.IOException;
import java.io.StringWriter;
import java.sql.ResultSet;

import java.util.Properties;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Text;

import DB.DBProvider;

/**
 * Servlet implementation class CreateXMLTimeTable
 */
public class CreateXMLTimeTable extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public CreateXMLTimeTable() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doPost(request,response);
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		
		String user = (request.getParameter("requestedUser")== null) ?
					  (String)request.getSession().getAttribute("username"):
					   request.getParameter("requestedUser");
		
		
		if (user == null) {
			//TODO
			response.sendError(HttpServletResponse.SC_BAD_REQUEST);
		}
		
		try {
			
			//Creating an empty XML Document
			DocumentBuilderFactory dbfac = DocumentBuilderFactory.newInstance();
			DocumentBuilder docBuilder = dbfac.newDocumentBuilder();
			Document doc = docBuilder.newDocument();
        
			//Creating the XML tree
        
			//create the root element and add it to the document
			Element root = doc.createElement("Calendar");
			doc.appendChild(root);

			//Retrieving user session from db
			Properties p = new Properties();
			p.load(getServletContext().getResourceAsStream("/WEB-INF/config"));
			DBProvider provider = new DBProvider(p);
			ResultSet res = provider.userCouresAndSessions(user);
			
			while(res.next()){
				
				//create session
				Element session = doc.createElement("Session");
				
				Element course = doc.createElement("Course");
				Text courseTitle = doc.createTextNode(res.getString(1));
				course.appendChild(courseTitle);
				session.appendChild(course);
				
				Element day = doc.createElement("Day");
				Text dayTitle = doc.createTextNode((new Integer(res.getInt(2)/10 + 1)).toString());
				day.appendChild(dayTitle);
				session.appendChild(day);
				
				Element Start = doc.createElement("Start");
				int start = res.getInt(2)%10;
				start = (start == 0) ? 17 : start + 7;
				Text StartTitle = doc.createTextNode(Integer.toString(start));
				Start.appendChild(StartTitle);
				session.appendChild(Start);
				
				int end = res.getInt(3)%10;
				end = (end == 0) ? 18 : end + 8;
				Element End = doc.createElement("End");
				Text EndTitle = doc.createTextNode(Integer.toString(end));
				End.appendChild(EndTitle);
				session.appendChild(End);
				
				//add session
				root.appendChild(session);
			}
			
			//Output the XML

            //set up a transformer
            TransformerFactory transfac = TransformerFactory.newInstance();
            Transformer trans = transfac.newTransformer();
            trans.setOutputProperty(OutputKeys.INDENT, "yes");

            //create string from xml tree
            StringWriter sw = new StringWriter();
            StreamResult result = new StreamResult(sw);
            DOMSource source = new DOMSource(doc);
            trans.transform(source, result);
            String xmlString = sw.toString();

            //return xml
            response.setContentType("text/xml");
            response.getWriter().println(xmlString);
			
		}catch (Exception e) {
			response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
			e.printStackTrace();} 
	}
	

}
